<?php

namespace App\Validator;

use App\Exception\ValidateFailException;
use Hyperf\Collection\Arr;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

class BaseValidator
{

    #[Inject]
    protected ValidatorFactoryInterface $validator;

    protected array $msg = [];

    protected array $attr = [];

    protected function validate($data, $rules=[])
    {
        $va = $this->validator->make($data, $rules, $this->msg, $this->attr);
        if ($va->fails()){
            throw new ValidateFailException($va->errors()->first());
        }
        return $va->validated();
    }

    protected function validatePage($data,  $rules=[])
    {
        $rules['page'] = ['required','integer','min:1'];
        $rules['ps'] = ['required','integer','min:1','max:500'];
        $ret = $this->validate($data,$rules);
        return [Arr::except($ret,['page','ps']), intval($ret['page']), intval($ret['ps'])];
    }
}